<template>
  <div class="sys-org-container" style="display:flex;">

      <div style="width: 100%;">
        <screeningCondition :inquireInfo="state.inquireInfo" @getChildren="getData">
          <el-button @click="openAddOrg" type="primary">新建</el-button>
        </screeningCondition>
      </div>
      <!-- 数据列表展示 -->

        <el-card class="full-table" shadow="hover" style="margin-top: 5px">
          <el-table :data="state.Data" class="el-table" v-loading="state.loading" row-key="id" default-expand-all
            :tree-props="{ children: 'children', hasChildren: 'hasChildren' }" border highlight-current-row
            @current-change="handleRowChange" :header-cell-style="{
              background: 'var(--el-color-primary)',
              height: '55px',
              color: '#fff',
              border: '1px solid #fff',
              fontWeight: 'bold',
              fontSize: '13px',
            }" :cell-style="{ padding: '2px' }">
            <el-table-column type="index" label="序号" align="center"></el-table-column>
            <el-table-column prop="materielNum" label="物料号" align="center" show-overflow-tooltip />
            <el-table-column prop="materielName" label="物料名称" header-align="center" show-overflow-tooltip
              align="center">
              <template v-slot="scope">
                {{ scope.row.materielName + ' ' + (scope.row.materielReamke ? scope.row.materielReamke : '') }}
              </template>
            </el-table-column>
            <el-table-column prop="materielSpecs" label="规格型号" align="center" show-overflow-tooltip />
            <el-table-column prop="materielMainUnit" label="主单位" align="center" width="60" show-overflow-tooltip />
            <el-table-column prop="materielAssistUnit" label="辅单位" header-align="center" show-overflow-tooltip
              align="center" width="60" />
            <!-- <el-table-column prop="materielType" label="物料分类" align="center" header-align="center"
              show-overflow-tooltip /> -->
            <el-table-column prop="quantityNeedCount" label="安全库存" align="center" width="80" header-align="center"
              show-overflow-tooltip>
              <template v-slot="scope">
                <span v-if="scope.row.quantityNeedCount">{{ scope.row.quantityNeedCount
                  }}</span>
                <span v-else>未设置</span>
              </template>
            </el-table-column>
            <el-table-column prop="inventoryDateTime" label="预警时间" align="center" width="80" header-align="center"
              show-overflow-tooltip>
              <template v-slot="scope">
                <span v-if="scope.row.inventoryDateTime">{{ scope.row.inventoryDateTime
                  }}</span>
                <span v-else>未设置</span>
              </template>
            </el-table-column>

            <el-table-column prop="materielLevelName" label="物料等级" align="center" width="80" header-align="center"
              show-overflow-tooltip></el-table-column>

            <el-table-column prop="materielReamke" label="物料备注" align="center" header-align="center"
              show-overflow-tooltip />

            <el-table-column prop="updateUserName" label="更新人" align="center" header-align="center"
              show-overflow-tooltip />
            <el-table-column label="操作" width="210" fixed="right" align="center" show-overflow-tooltip>
              <template #default="scope">
                <el-button size="small" type="primary" @click="openEdit(scope.row)">
                  编辑
                </el-button>
                <el-button size="small" @click="del(scope.row)" type="danger" v-auth="'material:delete'">
                  删除
                </el-button>
                <!-- <el-button size="small"  @click="openEditOrg(scope.row)" type="warning">管理
                </el-button> -->
              </template>
            </el-table-column>
          </el-table>

          <el-pagination v-model:current-page="state.queryParams.page" v-model:page-size="state.queryParams.pageSize"
            :page-sizes="[20, 30, 40, 50]" layout="->,total, sizes, prev, pager, next, jumper" :total="state.total"
            @size-change="handleSizeChange" @current-change="handleCurrentChange" :small="true" />
        </el-card>
    
    
    <!-- 新增物料 -->
    <el-drawer v-model="addDrawer" title="新增物料" :append-to-body="true" size="30%" @close="handleEditCancel()">
      <el-form :model="state.ruleForm" ref="ruleFormRef" label-width="auto" class="fl">
        <el-form-item label="物料号" prop="materielNum" :rules="[{ required: true, message: '物料号不能为空', trigger: 'blur' }]">
          <el-input v-model="state.ruleForm.materielNum" placeholder="物料号" clearable class="input" />
        </el-form-item>
        <el-form-item label="物料名称" prop="materielName"
          :rules="[{ required: true, message: '物料名称不能为空', trigger: 'blur' }]">
          <el-input v-model="state.ruleForm.materielName" placeholder="物料名称" clearable class="input" />
        </el-form-item>
        <el-form-item label="规格型号" prop="materielSpecs"
          :rules="[{ required: true, message: '规格型号不能为空', trigger: 'blur' }]">
          <el-input v-model="state.ruleForm.materielSpecs" placeholder="物料名称" clearable class="input" />
        </el-form-item>
        <el-form-item label="主单位">
          <el-select v-model="state.ruleForm.materielMainUnit" filterable clearable class="w100">
            <el-option v-for="item in state.MainUnit" :key="item" :label="item.value" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="辅单位">
          <el-select v-model="state.ruleForm.materielAssistUnit" filterable clearable class="w100">
            <el-option v-for="item in state.AssistUnit" :key="item" :label="item.value" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="物料分类" prop="materielType"
          :rules="[{ required: true, message: '物料分类不能为空', trigger: 'blur' }]">
          <el-select v-model="state.ruleForm.materielType" filterable clearable class="w100">
            <el-option v-for="item in state.class" :key="item" :label="item.value" :value="item.value" />
          </el-select>
        </el-form-item>

        <el-form-item label="物料等级" prop="materielLevelNum">
          <el-select v-model="state.ruleForm.materielLevelNum" filterable clearable class="w100">
            <el-option v-for="item in state.grade" :key="item.materielLevelNum" :label="item.materielLevelName"
              :value="item.materielLevelNum" />

          </el-select>

        </el-form-item>
        <el-form-item label="安全库存">
          <el-input v-model="state.ruleForm.quantityNeedCount" placeholder="安全库存" clearable class="input" />
        </el-form-item>
        <el-form-item label="物料预警时间">
          <el-input v-model="state.ruleForm.inventoryDateTime" placeholder="物料预警时间" clearable class="input" />
        </el-form-item>
        <el-form-item label="物料备注">
          <el-input v-model="state.ruleForm.materielReamke" placeholder="物料备注" clearable class="input" />
        </el-form-item>
        <el-form-item label="物料来源">
          <el-input v-model="state.ruleForm.materielSource" placeholder="物料来源" clearable class="input" />
        </el-form-item>
      </el-form>
      <div style="width: 100%; display: flex; justify-content: center; margin-top: 60px">
        <el-button @click="submit" type="primary" round style="width: 80px; height: 30px">确认</el-button>
        <el-button @click="addDrawer = false" round style="width: 80px; height: 30px">取消</el-button>
      </div>
    </el-drawer>
    <!-- 编辑物料 -->
    <el-drawer v-model="editDrawer" title="编辑物料" :append-to-body="true" size="30%" @close="handleEditCancel()">
      <el-form :model="state.ruleForm2" ref="editRuleFormRef" label-width="auto" class="fl">
        <el-form-item label="物料号" prop="materielNum" :rules="[{ required: true, message: '物料号不能为空', trigger: 'blur' }]">
          <el-input v-model="state.ruleForm2.materielNum" placeholder="物料数量" clearable class="input" disabled />
        </el-form-item>
        <el-form-item label="物料名称" prop="materielName"
          :rules="[{ required: true, message: '物料名称不能为空', trigger: 'blur' }]">
          <el-input v-model="state.ruleForm2.materielName" placeholder="物料名称" clearable class="input" />
        </el-form-item>
        <el-form-item label="规格型号">
          <el-select v-model="state.ruleForm2.materielSpecs" filterable clearable class="w100">
            <el-option v-for="item in state.specifications" :key="item" :label="item.value" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="主单位">
          <el-select v-model="state.ruleForm2.materielMainUnit" filterable clearable class="w100">
            <el-option v-for="item in state.MainUnit" :key="item" :label="item.value" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="辅单位">
          <el-select v-model="state.ruleForm2.materielAssistUnit" filterable clearable class="w100">
            <el-option v-for="item in state.AssistUnit" :key="item" :label="item.value" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="物料分类" prop="materielType"
          :rules="[{ required: true, message: '物料分类不能为空', trigger: 'blur' }]">
          <el-select v-model="state.ruleForm2.materielType" filterable clearable class="w100">
            <el-option v-for="item in state.class" :key="item" :label="item.value" :value="item.value" />
          </el-select>
        </el-form-item>

        <el-form-item label="物料等级" prop="materielLevelNum">
          <el-select v-model="state.ruleForm2.materielLevelNum" filterable clearable class="w100">
            <el-option v-for="item in state.grade" :key="item.materielLevelNum" :label="item.materielLevelName"
              :value="item.materielLevelNum" />
          </el-select>

        </el-form-item>
        <el-form-item label="物料备注">
          <el-input v-model="state.ruleForm2.materielReamke" placeholder="物料备注" clearable class="input" />
        </el-form-item>

        <el-form-item label="物料来源">
          <el-input v-model="state.ruleForm2.materielSource" placeholder="物料来源" clearable class="input" />
        </el-form-item>
      </el-form>
      <div style="width: 100%; display: flex; justify-content: center; margin-top: 60px">
        <el-button @click="submitEdit" type="primary" round style="width: 80px; height: 30px">确认</el-button>
        <el-button @click="handleEditCancel" round style="width: 80px; height: 30px">取消</el-button>
      </div>
    </el-drawer>
    <!-- tab选择框 -->
    <EditOrg ref="PutRef" :title="state.editOrgTitle" @handleQuery="getData(state.queryParams)" />
    <!-- 新增等级框 -->
    <EditClass ref="Ref" :title="state.editClassTitle" />
    <EditPos ref="editPosRef" :title="state.editPosTitle" @handleQuery="getData" :isEditing="state.isEditing" />
  </div>
</template>

<script lang="ts" setup name="sysOrg">
import { onMounted, reactive, ref } from "vue";
import { ElMessageBox, ElMessage } from "element-plus";
import { getAPI } from "/@/utils/axios-utils";
import { SysDictDataApi } from "/@/api-services/api";
import { WmsApi } from "/@/api/wh";
import screeningCondition from "/@/views/tools/screeningCondition.vue";
import EditOrg from "/@/views/system/material/component/tab.vue";
import EditClass from "/@/views/system/material/component/editClass.vue"
import EditPos from '/@/views/system/material/component copy/editPos.vue';
const editOrgRef1 = ref();
const supplementaryPrintRef = ref();
const addDrawer = ref(false);
const editDrawer = ref(false);
const Saferef = ref();
// 修改预警时间的tab框
const PutRef = ref();
const Ref = ref()
const ruleFormRef = ref();
const editRuleFormRef = ref();
const currentRow = ref();
const editPosRef = ref()
const state = reactive({
  isEditing: false,
  loading: false,
  Data: [], // 机构列表数据
  queryParams: {
    materielNum: "",
    materielType: "",
    materielSpecs: "",
    page: 1, //当前页
    pageSize: 20,
  },
  //物料等级
  grade: [],
  dialogVisible: false,
  editTitle: "",
  advanced: false,
  color: "#de2910",
  size: "14px",
  ruleForm: {},
  SaferuleForm: {},
  ruleForm2: {},
  value: {},
  class: [],
  total: 0,
  editClassTitle: '新增等级',
  editOrgTitle: '预警时间与安全库存修改',
  specifications: [],
  MainUnit: [],
  AssistUnit: [],
  inquireInfo: [
    {
      label: "物料号",
      value: "",
      key: "materielNum",
      options: [],
      type: "input",
    },
    {
      label: "物料名称",
      value: "",
      key: "materielName",
      options: [],
      type: "input",
    },
    {
      label: "物料规格",
      value: "",
      key: "materielSpecs",
      options: [],
      type: "input",
    },
  ],
});

onMounted(async () => {
  let resDicData = await getAPI(SysDictDataApi).apiSysDictDataDataListCodeGet(
    "code_gen_material_type"
  );
  state.class = resDicData.data.result;
  let resDicData1 = await getAPI(SysDictDataApi).apiSysDictDataDataListCodeGet(
    "code_gen_MainUnit_type"
  );
  state.MainUnit = resDicData1.data.result;
  let resDicData2 = await getAPI(SysDictDataApi).apiSysDictDataDataListCodeGet(
    "code_gen_AssistUnit_type"
  );
  state.AssistUnit = resDicData2.data.result;
  let resDicData3 = await getAPI(SysDictDataApi).apiSysDictDataDataListCodeGet(
    "code_gen_Spec_type"
  );
  state.specifications = resDicData3.data.result;
  // let resDicData4 = await getAPI(SysDictDataApi).apiSysDictDataDataListCodeGet(
  //   "code_gen_material_grade"
  // );
  // state.grade = resDicData4.data.result;
  WmsApi().getAllClass({ page: 1, pagesize: 10 }).then(
    res => {
      console.log(res);
      state.grade = res.data.result.items
    }
  )
  getData(state.queryParams);
});
// 打开新增页面
const openAddOrg = () => {
  // state.ruleForm2 = {};
  // addDrawer.value = true;
  state.editPosTitle = '添加新物料';
  editPosRef.value?.openDialog(state.ruleForm);
};

// 打开编辑页面
const openEdit = (row) => {

  // editDrawer.value = true;
  // state.ruleForm = row;
  state.isEditing = true;
  state.editPosTitle = '编辑物料';
  editPosRef.value?.openDialog(row);
};
// 查询操作
const getData = (value) => {
  state.value = value;
  console.log(value);

  var params = {
    page: state.queryParams.page,
    pageSize: state.queryParams.pageSize,
    materielNum: value?.materielNum,
    materielName: value?.materielName,
    materielType: value?.materielType,
    materielSpecs: value?.materielSpecs,
  };
  WmsApi()
    .MaterielPagePost(params)
    .then(function (res) {
      console.log(res);
      state.Data = res.data.result.items;
      state.total = res.data.result.total;
    })
    .catch(function (error) {
      console.log(error);
    });
};
//子传父
const openEditOrg = (row) => {

  PutRef.value?.openDialog(row);
};
const editClass = () => {
  Ref.value?.openDialog();
};
const handleSizeChange = (val) => {
  state.queryParams.pageSize = val;
  state.queryParams.materielNum = state.value.materielNum;
  state.queryParams.materielName = state.value.materielName;
  state.queryParams.productionDate = state.value.productionDate;
  getData(state.queryParams);
};
const handleCurrentChange = (newVal) => {
  state.queryParams.page = newVal;
  state.queryParams.materielNum = state.value.materielNum;
  state.queryParams.materielName = state.value.materielName;
  state.queryParams.productionDate = state.value.productionDate;
  getData(state.queryParams);
};

const toggleAdvanced = () => {
  state.advanced = !state.advanced;
  console.log(state.advanced);
};

const open = () => {
  state.ruleForm = {};
  addDrawer.value = true;
};

const submitEdit = () => {
  editRuleFormRef?.value.validate(async (valid, object) => {
    if (!valid) return false;
    await WmsApi()
      .MaterielPagePut(state.ruleForm2)

      .then(function (response) {
        console.log(response);
        ElMessage.success("修改成功");
        //then进行下一步操作
        getData(state.queryParams);
      })
      .catch(function (error) {
        console.log(error);
      });
    editDrawer.value = false;
  });
};

const handleRowChange = (val) => {
  currentRow.value = val;
};
//编辑取消时
const handleEditCancel = () => {
  editDrawer.value = false;
  // getData(state.queryParams)
}
const commit = () => {
  console.log(Saferef?.value);
  Saferef?.value.validate(async (valid, object) => {
    if (!valid) return false;
    await WmsApi()
      .PutSafeStorage(state.ruleForm2.materielNum, state.SaferuleForm.inputValue)
      .then(function (response) {
        console.log(response);
        ElMessage.success("修改成功");
        //then进行下一步操作
        getData(state.queryParams);
      })
      .catch(function (error) {
        console.log(error);
      });
    state.dialogVisible = false;
  });
};

// 删除
const del = (row) => {
  ElMessageBox.confirm(`确定删除该物料：【${row.materielName}】?`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      await WmsApi()
        .MaterielPageDelete({ id: row.id })
        .then(function (res) {
          ElMessage.success("删除成功");
          getData(state.queryParams);
        });
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "Delete canceled",
      });
    });
};
const openSupplementaryPrinting = () => {
  state.editTitle = "补打";
  supplementaryPrintRef.value?.openDialog({ status: 1 });
};

const submit = () => {
  ruleFormRef?.value.validate(async (valid, object) => {
    if (!valid) return false;
    await WmsApi()
      .MaterielPageAdd(state.ruleForm)
      .then(function (response) {
        ElMessage.success("新增成功");
        console.log(response);
        //then进行下一步操作
        getData(state.queryParams);
      })
      .catch(function (error) {
        console.log(error);
      });
    state.ruleForm = {}
    addDrawer.value = false;
  });
};
// 编辑
// const openEdit = (row) => {
//   editDrawer.value = true;
//   state.ruleForm2 = Object.assign({},row)
// };
const PutSafe = (row) => {
  state.dialogVisible = true;
  state.ruleForm2.materielNum = row.materielNum;
};

</script>
<style lang="scss" scoped>
.right-handle-group {
  width: 500px;
  margin-top: 5px;
}

.fl {
  width: 60%;
  margin: 20px 80px;
}

.right-handle-group1 {
  margin-top: -84px;
  margin-right: 340px;
  float: right;
}

.heightTall {
  height: 150px;
}

.heightlast {
  height: 100px;
}

.container {
  margin-top: 15px;
  width: 100%;
  display: flex;
  flex-direction: column;
  height: calc(100% - 82px);
}

.table {
  width: 100%;
  flex: 1;
  height: 100%;
}

.el-table {
  width: 100%;

  /* overflow: auto; */
}
</style>